import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Chris Hansen
 */
public class Chris  extends Actor implements Runnable
{
    int attackVariable;
    retroWorld theWorld;
    Simon simon;
    Health health;
    ChrisEye e1;
    ChrisEye e2;
  
    
    private boolean alive;
    
    private volatile Thread t;
    
    public Chris()
    {   
        
    }
    
    boolean acted=false;

    /**
     * Act - do whatever the Chris wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        if(!acted)
          theWorld.chrisSounds();
          
        acted=true;
    } 
    
    public void run()
    {
        int mod = 100;
        int attackCounter = 0;
        
        while(alive)
        {
            
            if(!simon.isAlive())
                removeFromWorld();

            attackCounter++;
            
            if(attackCounter%mod==0){
                mod=Greenfoot.getRandomNumber(100)+100;
                attackCounter=1; 
                attack();
            }
            
            try {
                t.sleep(20);
            } catch (InterruptedException e) {}
        }
    }
    
    public void addedToWorld(World world)
    {
        theWorld = (retroWorld)world;
        simon = theWorld.getSimon();
        health = theWorld.getHealth();
       
        e1=new ChrisEye(this);
        e2=new ChrisEye(this);
        
        world.addObject(e1,getX()+9,getY()-103);
        world.addObject(e2,getX()+35,getY()-102);
        
        //The ChatLog in Chris's hand is his only weak spot
        theWorld.addObject(new ChatLog(this), getX()-35, getY()-40);
  
        alive = true;
        t = new Thread(this);
        t.start();     
    }
    
    /** Chris Hansen's Stool attack, Five randomly fall from the sky
     *  or one falls on Simon
     *  
     */
    public void attack()
    {
        attackVariable = Greenfoot.getRandomNumber(2);
        
        if (attackVariable == 0)
        {
            theWorld.addObject(new Stool(), simon.getX(), 50);                      
        }
        else
        {
            theWorld.addObject(new Stool(), (Greenfoot.getRandomNumber(450) + 50), 50);
            theWorld.addObject(new Stool(), (Greenfoot.getRandomNumber(450) + 50), 50);           
            theWorld.addObject(new Stool(), (Greenfoot.getRandomNumber(450) + 50), 50);
            theWorld.addObject(new Stool(), (Greenfoot.getRandomNumber(450) + 50), 50);
            theWorld.addObject(new Stool(), (Greenfoot.getRandomNumber(450) + 50), 50);   
        }
    }
    
    public void removeFromWorld(){
       theWorld.stopped();
       alive=false;
       e1.removeFromWorld();
       e2.removeFromWorld();
       theWorld.removeObject(this);
       t=null;
        
    }
}
